package com.tiger.cloud.controller.crm;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.tiger.cloud.common.jpush.JpushInterface;
import com.tiger.cloud.common.mapper.JsonMapper;
import com.tiger.cloud.common.mybatis.BaseController;
import com.tiger.cloud.enums.DeleteEnum;
import com.tiger.cloud.enums.RecommandListAcceptStatus;
import com.tiger.cloud.enums.RecommandListStatus;
import com.tiger.cloud.filter.CurrentUserId;
import com.tiger.cloud.filter.CurrentUserLoginId;
import com.tiger.cloud.filter.IgnoreAuth;
import com.tiger.cloud.form.UserCompanyInfoForm;
import com.tiger.cloud.model.crm.AreaRecommandRemove;
import com.tiger.cloud.model.crm.MailList;
import com.tiger.cloud.model.crm.RecommandList;
import com.tiger.cloud.model.crm.User;
import com.tiger.cloud.model.system.DataObject;
import com.tiger.cloud.model.system.SysScheduleJob;
import com.tiger.cloud.service.crm.IAreaRecommandRemoveService;
import com.tiger.cloud.service.crm.IMailListService;
import com.tiger.cloud.service.crm.IRecommandListService;
import com.tiger.cloud.service.crm.IUserService;
import com.tiger.cloud.service.crm.UserCompanyInfoService;
import com.tiger.cloud.service.system.ISysScheduleJobService;
import com.tiger.cloud.util.DateTimeUtil;
import com.tiger.cloud.util.ErrorCode;
import com.tiger.cloud.util.Page;
import com.tiger.cloud.util.Response;
import com.tiger.cloud.util.ResponseUtil;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

/**
 * 好友推荐/申请
 */
@Controller
@RequestMapping(value = "recommandList")
@Api(value = "好友推荐/申请",tags = "好友推荐/申请")
public class RecommandListController extends BaseController {

	@Autowired
	private IRecommandListService recommandListService;
	@Autowired
	private IAreaRecommandRemoveService areaRecommandRemoveService;
	@Autowired
	private IMailListService mailListService;
	@Autowired
	private JpushInterface jpushInterface;
	@Autowired
	private ISysScheduleJobService sysScheduleJobService; 
	@Autowired
	private IUserService userService;
	@Autowired
	private UserCompanyInfoService userCompanyInfoService;
	
	/**
	 * 增量分页获取要事纪要
	 */
	@RequestMapping(value = "find", method = RequestMethod.POST)
	@ResponseBody
	@CrossOrigin
	@ApiOperation(value = "增量分页获取推荐/申请",notes = "增量分页获取要推荐/申请")
	public Response find(@ApiParam(name="id",value="用户id",hidden=true) @CurrentUserId Long userId,
			@RequestBody RecommandList recommandList){
		logger.debug("RecommandListController find request userId,recommandList:"+userId+"***"+recommandList);
		recommandList.getStatusIn().add(RecommandListStatus.PEND_VERIF);//待验证
		recommandList.getStatusIn().add(RecommandListStatus.CREATED);//已经添加
		recommandList.setUserIdOr(userId);
		logger.debug("RecommandListController find recommandList.isHasAddressbook():"+recommandList.isHasAddressbook());
		if(recommandList.isHasAddressbook()){//通讯录请求
			recommandList.getStatusIn().add(RecommandListStatus.WAIT_CREATE);//待添加
		}else{
			recommandList.getAcceptStatusIn().add(RecommandListAcceptStatus.WAIT_ACCEPT);//待接受
			recommandList.getAcceptStatusIn().add(RecommandListAcceptStatus.ACCEPTED);//已接受
			recommandList.setIsDelete(DeleteEnum.NOMAIL);
			recommandList.setAcceptIsDelete(DeleteEnum.NOMAIL);
		}
		logger.debug("RecommandListController find recommandListService.page[recommandList]:"+recommandList);
		Page<RecommandList> datas = recommandListService.page(recommandList);
		datas.setCurrentUserId(userId);
		//删除掉自己本身的
		List<RecommandList> list = datas.getData();
		Iterator<RecommandList> it = list.iterator();
		while (it.hasNext()) {
			RecommandList re = it.next();
			if (re.getRecommandId().equals(userId) && re.getUserId().equals(userId)) {
				it.remove();
			}
		}
		logger.debug("RecommandListController find response[datas]:"+datas);
		return ResponseUtil.ok(datas);
	}
	
	
	
	/**
	 * 删除区域人脉
	 */
	@RequestMapping(value = "areaRecommandRemove", method = RequestMethod.POST)
	@ResponseBody
	@CrossOrigin
	@ApiOperation(value = "删除区域人脉",notes = "删除区域人脉")
	public Response areaRecommandRemove(@ApiParam(name="id",value="用户id",hidden=true) @CurrentUserId Long userId,@RequestBody AreaRecommandRemove areaRecommandRemove){
		if(areaRecommandRemove.getBeRemoveId()==null){
			return ResponseUtil.error(ErrorCode.PARAMETER_INVALID,"reRemoveId必传");
		}
		areaRecommandRemove.setClientId(userId);
		areaRecommandRemove.setCreateTime(new Date());
		areaRecommandRemoveService.insert(areaRecommandRemove);
		return ResponseUtil.ok();
	}
	
	/**
	 * 首页友圈(区域人脉)
	 */
	@IgnoreAuth
	@RequestMapping(value = "areaRecommands", method = RequestMethod.POST)
	@ResponseBody
	@CrossOrigin
	@ApiOperation(value = "首页友圈(区域人脉)",notes = "首页友圈(区域人脉)")
	public Response areaRecommands(@ApiParam(name="id",value="用户id",hidden=true) @CurrentUserId Long userId,@RequestBody RecommandList recommandList){
		Integer  bizType=recommandList.getTypeId()==null?null:Integer.parseInt(recommandList.getTypeId());
		
		List<RecommandList> recommandLists =recommandListService.findAreaRecommandList(bizType,recommandList.getProvinceId(), recommandList.getCityId(), recommandList.getDistrictId(), userId, recommandList.getLimitStart(), recommandList.getLimitEnd());
		System.out.println("recommandLists:recommandLists:recommandLists:recommandLists:"+recommandLists);
		return ResponseUtil.ok(recommandLists);
	}
	
	
	
	/**
	 * 首页友圈(区域人脉)
	 */
	@IgnoreAuth
	@RequestMapping(value = "areaRecommands1", method = RequestMethod.POST)
	@ResponseBody
	@CrossOrigin
	@ApiOperation(value = "首页友圈(区域人脉)",notes = "首页友圈(区域人脉)")
	public Response areaRecommands1(@ApiParam(name="id",value="用户id",hidden=true) @CurrentUserId Long userId,@RequestBody RecommandList recommandList){
		Integer  bizType=recommandList.getTypeId()==null?null:Integer.parseInt(recommandList.getTypeId());
		recommandList.setLimitEnd(20);
		List<RecommandList> recommandLists =recommandListService.findAreaRecommandList(bizType,recommandList.getProvinceId(), recommandList.getCityId(), recommandList.getDistrictId(), userId, recommandList.getLimitStart(), recommandList.getLimitEnd());
		System.out.println("recommandLists:recommandLists:recommandLists:recommandLists:"+recommandLists);
		return ResponseUtil.ok(recommandLists);
	}
	
	
	
	/**
	 * 首页友圈(区域人脉)
	 * 查询总数
	 */
	@RequestMapping(value = "areaRecommandCount", method = RequestMethod.POST)
	@ResponseBody
	@CrossOrigin
	@ApiOperation(value = "首页友圈(区域人脉)",notes = "首页友圈(区域人脉)")
	public Response areaRecommandCount(@ApiParam(name="id",value="用户id",hidden=true) @CurrentUserId Long userId,@RequestBody RecommandList recommandList){
		long recommandLists =recommandListService.findAreaRecommandCount(recommandList.getProvinceId(), recommandList.getCityId(), recommandList.getDistrictId(), userId, recommandList.getLimitStart(), recommandList.getLimitEnd());
		return ResponseUtil.ok(recommandLists);
	}
	
	/**
	 * 增量好友推荐/申请
	 */
	@RequestMapping(value = "incrementRecommands", method = RequestMethod.POST)
	@ResponseBody
	@CrossOrigin
	@ApiOperation(value = "增量好友推荐/申请",notes = "增量好友推荐/申请")
	public Response incrementRecommands(@ApiParam(name="id",value="用户id",hidden=true) @CurrentUserId Long userId,@RequestBody RecommandList recommandList){
		recommandList.setIsDelete(DeleteEnum.NOMAIL);
		recommandList.setAcceptIsDelete(DeleteEnum.NOMAIL);
		recommandList.setUserIdOr(userId);
		List<RecommandList> recommandLists = recommandListService.find(recommandList);
		return ResponseUtil.ok(recommandLists);
	}
	
	/**
	 * 运行通讯录匹配
	 */
	@RequestMapping(value = "runMailListsMatch", method = RequestMethod.POST)
	@ResponseBody
	@CrossOrigin
	@ApiOperation(value = "运行通讯录匹配",notes = "运行通讯录匹配")
	@IgnoreAuth
	public Response runMailListsMatch(@ApiParam(name="id",value="用户id",hidden=true) @CurrentUserId Long userId){
		mailListService.runMailListsMatch(userId);
		return ResponseUtil.ok();
	}
	
	/**
	 * 清空运行通讯录匹配
	 */
	@RequestMapping(value = "clearMailListsMatch", method = RequestMethod.POST)
	@ResponseBody
	@CrossOrigin
	@ApiOperation(value = "清空运行通讯录匹配",notes = "清空运行通讯录匹配")
	@IgnoreAuth
	public Response clearMailListsMatch(){
		mailListService.clearMailListsMatch();
		return ResponseUtil.ok();
	}
	
	/**
	 * 发送通讯录到服务器
	 */
	@RequestMapping(value = "sendMailList", method = RequestMethod.POST)
	@ResponseBody
	@CrossOrigin
	@ApiOperation(value = "发送通讯录到服务器",notes = "发送通讯录到服务器")
	public Response sendMailList(@ApiParam(name="id",value="用户id",hidden=true) @CurrentUserId Long userId,@RequestBody HashSet<String> mobiles,@ApiParam(name="id",value="用户id",hidden=true) @CurrentUserLoginId String  loginId){
		if(mobiles==null||mobiles==null||mobiles.size()==0){
			return ResponseUtil.error(ErrorCode.PARAMETER_INVALID,"Mobiles 不能为空！");
		}
		List<MailList> mailLists=new ArrayList<MailList>();
		for (String mobile : mobiles) {
			MailList mailList=new MailList();
			mailList.setUserId(userId);
			if((!StringUtils.isEmpty(mobile)) && (!loginId.equals(mobile))){
				mailList.setMobile(mobile);
				mailLists.add(mailList);
			}
		}
		try {
			if(mailLists.size()==0){
				return ResponseUtil.ok();
			}
			if(mailListService.addMailLists(mailLists, userId)){
				//mailListService.runMailListsMatch(userId);
				return ResponseUtil.ok();
			};
		} catch (Exception e) {
			e.printStackTrace();
		}
		return ResponseUtil.ok();
	}
	
	/**
	 * 同意申请
	 * 个人用户
	 * <p>Title: RecommandListController.java</p>
	 * @author huxusheng  
	 * @date 2018年5月24日  
	 * @param userId
	 * @param request
	 * @param recommandList
	 * @return
	 */
	@RequestMapping(value = "acceptRequest", method = RequestMethod.POST)
	@ResponseBody
	@CrossOrigin
	@ApiOperation(value = "同意申请",notes = "同意申请")
	public Response acceptRequest(@ApiParam(name="id",value="用户id",hidden=true) @CurrentUserId Long userId,
			HttpServletRequest request,@RequestBody  RecommandList recommandList){
		if(recommandList.getId()!=null&&recommandList.getId()>0){
			RecommandList findRecommandList=recommandListService.get(recommandList.getId());
			if(findRecommandList==null){
				return ResponseUtil.error(ErrorCode.OBJECT_NOT_EXITS,"请求添加不存在!");
			}
			if(findRecommandList.getAcceptStatus()==RecommandListAcceptStatus.ACCEPTED){
				return ResponseUtil.error("已经添加");
			}
			if(recommandListService.acceptRequest(findRecommandList,userId)){
				User user=userService.get((userId.longValue()==findRecommandList.getUserId().longValue())?userId:findRecommandList.getRecommandId());
				String msString=user.getUserName()+"已经接受您的添加请求，从现在起，你们已经进入彼此的人脉圈，可以随时保持联系，祝你们 经常携手合作！";
				
				User cUser=userService.get((user.getId().longValue()==findRecommandList.getUserId().longValue())?findRecommandList.getRecommandId():findRecommandList.getUserId());
				List<String> clientList=new ArrayList<String>();
				clientList.add(cUser.getJpushCode());
				
				Map<String, Object> data=new HashMap<String, Object>();
				Map<String, Object> params=new HashMap<String, Object>();
				params.put("id", null);
				params.put("content",msString);
				data.put("type", "1");
				data.put("data", JsonMapper.nonDefaultMapper().toJson(params));
				jpushInterface.sendAllClientsPushMessage(clientList,"notification", data);
				
				
				java.util.Date  date=new java.util.Date();
				DataObject dataObject=new DataObject();
				dataObject.setJpushCode(clientList);
				dataObject.setMsg(msString);
				
				try {
					date=DateTimeUtil.addMinutes(date, 10);
					String cron=date.getSeconds()+ " "+DateTimeUtil.getMinutesOfHour(date)+" "+DateTimeUtil.getHoursOfDay(date)+" "+DateTimeUtil.getDayOfMonth(date)+" "+DateTimeUtil.getMonthOfYear(date)+" ? "+DateTimeUtil.getYearOfDate(date);
					SysScheduleJob scheduleJob1= new SysScheduleJob();
					scheduleJob1.setCronExpression(cron);
					scheduleJob1.setJobGroup("com.tiger.cloud.service.system.TaskExcutor");
					scheduleJob1.setJobName("TaskExcutor.pushMsg.01."+findRecommandList.getUserId()+"."+findRecommandList.getRecommandId());
					scheduleJob1.setTempId(JsonMapper.nonDefaultMapper().toJson(dataObject));
					scheduleJob1.setMethodName("pushMsg");
					sysScheduleJobService.addJob(scheduleJob1);
					
					date=DateTimeUtil.addMinutes(date, 10);
					cron=date.getSeconds()+ " "+DateTimeUtil.getMinutesOfHour(date)+" "+DateTimeUtil.getHoursOfDay(date)+" "+DateTimeUtil.getDayOfMonth(date)+" "+DateTimeUtil.getMonthOfYear(date)+" ? "+DateTimeUtil.getYearOfDate(date);
					SysScheduleJob scheduleJob2= new SysScheduleJob();
					scheduleJob2.setCronExpression(cron);
					scheduleJob2.setJobGroup("com.tiger.cloud.service.system.TaskExcutor");
					scheduleJob2.setJobName("TaskExcutor.pushMsg.02."+findRecommandList.getUserId()+"."+findRecommandList.getRecommandId());
					scheduleJob2.setTempId(JsonMapper.nonDefaultMapper().toJson(dataObject));
					scheduleJob2.setMethodName("pushMsg");
					sysScheduleJobService.addJob(scheduleJob2);
				} catch (Exception e) {
					e.printStackTrace();
				}
				return ResponseUtil.ok();
			}
			return ResponseUtil.error();
		}
		return ResponseUtil.error("参数错误,请重试!");
	}
	
	
	
	/**
	 * 申请同行为好友
	 */
	@RequestMapping(value = "recommandUser", method = RequestMethod.POST)
	@ResponseBody
	@CrossOrigin
	@ApiOperation(value = "扫码/手机号申请好友",notes = "扫码/手机号申请好友")
	public Response recommandUser(@ApiParam(name="id",value="用户id",hidden=true) @CurrentUserId Long userId,HttpServletRequest request,@RequestBody  RecommandList recommandList){
		if(StringUtils.isEmpty(recommandList.getRemark())){
			recommandList.setRemark("请求添加为好友");
		}
		if(recommandList.getRecommandId()==null||recommandList.getRecommandId()<0){
			return ResponseUtil.error(ErrorCode.PARAMETER_INVALID,"recommandId必传!");
		}
//		if(recommandList.getRecommandWay()==null||recommandList.getRecommandWay()==ResourceTypeEnum.ADDRESSBOOK){
//			return ResponseUtil.error(ErrorCode.PARAMETER_INVALID,"recommandWay必须是0(CRM用户匹配-->好友申请)/1(扫码)");
//		}
		recommandList.setUserId(userId);
		recommandList.setAcceptDate(null);
		recommandList.setRecommandDate(new Date());
		recommandList.setStatus(RecommandListStatus.PEND_VERIF);
		recommandList.setRemark(recommandList.getRemark());
		recommandList.setAcceptStatus(RecommandListAcceptStatus.WAIT_ACCEPT);
		if(recommandListService.recommandUser(recommandList,userId)){
			return ResponseUtil.ok();
		}
		return ResponseUtil.error();
	}

	/**
	 * 删除通讯录
	 */
	@RequestMapping(value = "delete", method = RequestMethod.POST)
	@ResponseBody
	@CrossOrigin
	@ApiOperation(value = "删除申请记录",notes = "删除申请记录")
	public Response delete(@ApiParam(name="id",value="用户id",hidden=true) @CurrentUserId Long userId,@RequestBody  RecommandList recommandList){
		if(recommandList.getId()!=null&&recommandList.getId()>0){
			RecommandList deleteEntity=recommandListService.get(recommandList.getId());
			if(deleteEntity==null||deleteEntity.getRecommandId().longValue() != userId.longValue()){
				return ResponseUtil.error("参数错误,请重试!");
			}
			if(deleteEntity.getAcceptStatus() == RecommandListAcceptStatus.ACCEPTED){
				return ResponseUtil.error("该用户已添加,无法删除!");
			}
			RecommandList  recommand = new RecommandList();
			recommand.setId(recommandList.getId());
			if(recommandListService.remove(recommand)>0){
				return ResponseUtil.ok();
			}
			return ResponseUtil.error();
		}
		return ResponseUtil.error("参数错误,请重试!");
	}
	/**
	 * 统计用户未接受好友申请数量
	 */
	@RequestMapping(value = "findNotAccept", method = RequestMethod.POST)
	@ResponseBody
	@CrossOrigin
	@ApiOperation(value = "统计用户未接受好友申请数量",notes = "统计用户未接受好友申请数量")
	public Response findNotAccept(@ApiParam(name="id",value="用户id",hidden=true) @CurrentUserId Long userId){
		if(null == userId){
			return ResponseUtil.error("未获取到用户信息");
		}
		RecommandList recommandList = new RecommandList();
		recommandList.setRecommandId(userId);
		recommandList.setAcceptStatus(RecommandListAcceptStatus.WAIT_ACCEPT);
		long userNotAcceptCount = recommandListService.findNotAccept(recommandList);
		return ResponseUtil.ok(userNotAcceptCount);
	}
	
	
	
	
	/**
	 * 5月23新增版本  start ↓↓↓↓↓↓↓↓↓↓↓↓↓↓ 
	 */
	
	/**
	 * 查询个人圈或者企业圈"
	 * <p>Title: RecommandListController.java</p>
	 * @author huxusheng  
	 * @date 2018年5月23日  
	 * @param recommandList
	 * @param userId and usetType
	 * @return
	 */
	@IgnoreAuth
	@CrossOrigin
	@RequestMapping(value = "/byPersonalOrEnterprise", method = RequestMethod.POST)
	@ResponseBody
	@ApiOperation(value = "查询个人圈或者企业圈",notes = "查询个人圈或者企业圈")
	public Response byPersonalOrEnterprise(@RequestBody User user) {
		logger.debug("RecommandListController findRecommandList request[user]:"+user);
		Response result = new Response();
		if ( null == user.getId() || user.getId() < 1) {
			result = ResponseUtil.error(ErrorCode.ID_NULL);
		}
		else if ( null == user.getUserType() ) {
			result = ResponseUtil.error(ErrorCode.USER_TYPE_NULL);
		}
		else {
			Map<String, Object> paramMap = new HashMap<String, Object>();
			
			paramMap.put("userId", user.getId());			//用户id
			paramMap.put("userType", user.getUserType());	//查询个人还是企业
			/*paramMap.put("limitStart", user.getLimitStart());
			paramMap.put("limitEnd", 20);*/
			List<UserCompanyInfoForm> list = userCompanyInfoService.byPersonalOrEnterprise(paramMap);
			result.setData(list);
		}
		logger.debug("RecommandListController findRecommandList response[result]:"+result);
		return result;
	}
	
	
	
}